import { useEffect, useMemo } from 'react';
import { useScheduleStore } from './scheduleStore';
import { scheduleSelectors, scheduleCalculators } from './scheduleSelectors';
import type { IScheduleTemplate } from '@/types/schedule/scheduleTemplate';
import type { IScheduleInstance } from '@/types/schedule/scheduleInstance';
import { ScheduleViewTypeEnum } from '@/types/schedule/enums';

/**
 * 课表管理Hook
 * @description 提供课表数据管理的便捷Hook
 */
export const useScheduleManagement = () => {
  const store = useScheduleStore();
  
  // 初始化数据
  useEffect(() => {
    if (store.templates.length === 0) {
      store.fetchTemplates();
    }
    if (store.instances.length === 0) {
      store.fetchInstances();
    }
  }, []);
  
  return {
    // 数据
    templates: scheduleSelectors.getFilteredTemplates(store),
    instances: scheduleSelectors.getFilteredInstances(store),
    selectedTemplate: store.selectedTemplate,
    selectedInstance: store.selectedInstance,
    
    // 加载状态
    isTemplateLoading: scheduleSelectors.isTemplateLoading(store),
    isInstanceLoading: scheduleSelectors.isInstanceLoading(store),
    isConflictLoading: scheduleSelectors.isConflictLoading(store),
    
    // 错误状态
    templateError: scheduleSelectors.getTemplateError(store),
    instanceError: scheduleSelectors.getInstanceError(store),
    conflictError: scheduleSelectors.getConflictError(store),
    
    // 冲突信息
    conflicts: scheduleSelectors.getConflicts(store),
    hasConflicts: scheduleSelectors.hasConflicts(store),
    
    // UI状态
    showTemplateForm: store.showTemplateForm,
    templateFormMode: store.templateFormMode,
    showInstanceDetail: store.showInstanceDetail,
    showConflictDialog: store.showConflictDialog,
    
    // 操作方法
    addTemplate: store.addTemplate,
    updateTemplate: store.updateTemplate,
    deleteTemplate: store.deleteTemplate,
    generateInstances: store.generateInstances,
    
    completeInstance: store.completeInstance,
    cancelInstance: store.cancelInstance,
    addMakeupInstance: store.addMakeupInstance,
    
    checkTemplateConflict: store.checkTemplateConflict,
    checkInstanceConflict: store.checkInstanceConflict,
    clearConflicts: store.clearConflicts,
    
    selectTemplate: store.selectTemplate,
    selectInstance: store.selectInstance,
    
    // UI操作
    openCreateTemplateForm: () => {
      store.setTemplateFormMode('create');
      store.setShowTemplateForm(true);
    },
    openEditTemplateForm: (template: IScheduleTemplate) => {
      store.selectTemplate(template);
      store.setTemplateFormMode('edit');
      store.setShowTemplateForm(true);
    },
    closeTemplateForm: () => store.setShowTemplateForm(false),
    
    openInstanceDetail: (instance: IScheduleInstance) => {
      store.selectInstance(instance);
      store.setShowInstanceDetail(true);
    },
    closeInstanceDetail: () => store.setShowInstanceDetail(false),
    
    openConflictDialog: () => store.setShowConflictDialog(true),
    closeConflictDialog: () => store.setShowConflictDialog(false),
    
    // 筛选操作
    updateTemplateFilters: store.updateTemplateFilters,
    setTemplateSearchKeyword: store.setTemplateSearchKeyword,
    resetTemplateFilters: store.resetTemplateFilters,
    
    updateInstanceFilters: store.updateInstanceFilters,
    setInstanceSearchKeyword: store.setInstanceSearchKeyword,
    resetInstanceFilters: store.resetInstanceFilters,
    
    // 刷新数据
    refresh: store.refresh
  };
};

/**
 * 课表视图Hook
 * @description 提供课表视图相关的状态和操作
 */
export const useScheduleView = () => {
  const store = useScheduleStore();
  
  return {
    // 视图状态
    viewType: store.viewType,
    selectedDate: store.selectedDate,
    selectedStudentIds: store.selectedStudentIds,
    showConflictDetection: store.showConflictDetection,
    
    // 视图数据
    selectedDateInstances: scheduleSelectors.getSelectedDateInstances(store),
    selectedStudentsInstances: scheduleSelectors.getSelectedStudentsInstances(store),
    selectedStudentsDateInstances: scheduleSelectors.getSelectedStudentsDateInstances(store),
    
    // 视图操作
    setViewType: store.setViewType,
    setSelectedDate: store.setSelectedDate,
    setSelectedStudentIds: store.setSelectedStudentIds,
    toggleStudentSelection: store.toggleStudentSelection,
    setShowConflictDetection: store.setShowConflictDetection,
    
    // 便捷方法
    switchToDayView: () => store.setViewType(ScheduleViewTypeEnum.DAY),
    switchToWeekView: () => store.setViewType(ScheduleViewTypeEnum.WEEK),
    switchToMonthView: () => store.setViewType(ScheduleViewTypeEnum.MONTH),
    switchToMixedView: () => store.setViewType(ScheduleViewTypeEnum.MIXED),
    
    goToToday: () => store.setSelectedDate(new Date().toISOString().split('T')[0]),
    goToPreviousDay: () => {
      const currentDate = new Date(store.selectedDate);
      currentDate.setDate(currentDate.getDate() - 1);
      store.setSelectedDate(currentDate.toISOString().split('T')[0]);
    },
    goToNextDay: () => {
      const currentDate = new Date(store.selectedDate);
      currentDate.setDate(currentDate.getDate() + 1);
      store.setSelectedDate(currentDate.toISOString().split('T')[0]);
    }
  };
};

/**
 * 课表统计Hook
 * @description 提供课表统计数据
 */
export const useScheduleStats = (studentId?: string) => {
  const store = useScheduleStore();
  
  const templateStats = useMemo(() => 
    scheduleSelectors.getTemplateStats(store), 
    [store.templates]
  );
  
  const instanceStats = useMemo(() => 
    scheduleSelectors.getInstanceStats(store), 
    [store.instances]
  );
  
  const studentStats = useMemo(() => 
    studentId ? scheduleSelectors.getStudentStats(store, studentId) : null,
    [store.templates, store.instances, studentId]
  );
  
  return {
    templateStats,
    instanceStats,
    studentStats
  };
};

/**
 * 课表选择Hook
 * @description 提供课表选择相关的状态和操作
 */
export const useScheduleSelection = () => {
  const store = useScheduleStore();
  
  return {
    // 选择状态
    selectedTemplateIds: store.selectedTemplateIds,
    selectedInstanceIds: store.selectedInstanceIds,
    selectedTemplate: store.selectedTemplate,
    selectedInstance: store.selectedInstance,
    
    // 选择操作
    selectTemplate: store.selectTemplate,
    toggleTemplateSelection: store.toggleTemplateSelection,
    selectAllTemplates: store.selectAllTemplates,
    clearTemplateSelection: store.clearTemplateSelection,
    
    selectInstance: store.selectInstance,
    toggleInstanceSelection: store.toggleInstanceSelection,
    selectAllInstances: store.selectAllInstances,
    clearInstanceSelection: store.clearInstanceSelection,
    
    // 批量操作
    showBatchPanel: store.showBatchPanel,
    setShowBatchPanel: store.setShowBatchPanel,
    
    // 便捷方法
    hasSelectedTemplates: store.selectedTemplateIds.length > 0,
    hasSelectedInstances: store.selectedInstanceIds.length > 0,
    selectedTemplateCount: store.selectedTemplateIds.length,
    selectedInstanceCount: store.selectedInstanceIds.length,
    
    isTemplateSelected: (templateId: string) => 
      scheduleSelectors.isTemplateSelected(store, templateId),
    isInstanceSelected: (instanceId: string) => 
      scheduleSelectors.isInstanceSelected(store, instanceId)
  };
};

/**
 * 课表冲突检测Hook
 * @description 提供冲突检测相关的功能
 */
export const useScheduleConflict = () => {
  const store = useScheduleStore();
  
  return {
    // 冲突状态
    conflicts: scheduleSelectors.getConflicts(store),
    hasConflicts: scheduleSelectors.hasConflicts(store),
    isConflictLoading: scheduleSelectors.isConflictLoading(store),
    conflictError: scheduleSelectors.getConflictError(store),
    
    // 冲突检测操作
    checkTemplateConflict: store.checkTemplateConflict,
    checkInstanceConflict: store.checkInstanceConflict,
    clearConflicts: store.clearConflicts,
    
    // UI状态
    showConflictDetection: store.showConflictDetection,
    showConflictDialog: store.showConflictDialog,
    setShowConflictDetection: store.setShowConflictDetection,
    setShowConflictDialog: store.setShowConflictDialog
  };
};

/**
 * 课表筛选Hook
 * @description 提供筛选功能的便捷Hook
 */
export const useScheduleFilter = () => {
  const store = useScheduleStore();
  
  return {
    // 模板筛选
    templateFilters: store.templateFilters,
    updateTemplateFilters: store.updateTemplateFilters,
    setTemplateSearchKeyword: store.setTemplateSearchKeyword,
    resetTemplateFilters: store.resetTemplateFilters,
    
    // 实例筛选
    instanceFilters: store.instanceFilters,
    updateInstanceFilters: store.updateInstanceFilters,
    setInstanceSearchKeyword: store.setInstanceSearchKeyword,
    resetInstanceFilters: store.resetInstanceFilters,
    
    // 筛选结果
    filteredTemplates: scheduleSelectors.getFilteredTemplates(store),
    filteredInstances: scheduleSelectors.getFilteredInstances(store),
    
    // 便捷方法
    filterByStudent: (studentId: string) => {
      store.updateTemplateFilters({ studentId });
      store.updateInstanceFilters({ studentId });
    },
    filterByCourse: (courseId: string) => {
      store.updateTemplateFilters({ courseId });
      store.updateInstanceFilters({ courseId });
    },
    filterByDateRange: (dateFrom: string, dateTo: string) => {
      store.updateInstanceFilters({ dateFrom, dateTo });
    },
    clearAllFilters: () => {
      store.resetTemplateFilters();
      store.resetInstanceFilters();
    }
  };
};

/**
 * 课表计算Hook
 * @description 提供课表相关的计算功能
 */
export const useScheduleCalculator = () => {
  return {
    // 计算方法
    calculateTemplateProgress: scheduleCalculators.calculateTemplateProgress,
    calculateRemainingCount: scheduleCalculators.calculateRemainingCount,
    isTimeOverlap: scheduleCalculators.isTimeOverlap,
    getDateRange: scheduleCalculators.getDateRange,
    getDayOfWeek: scheduleCalculators.getDayOfWeek,
    getWeekStartDate: scheduleCalculators.getWeekStartDate,
    getWeekDates: scheduleCalculators.getWeekDates
  };
};